package com.example.pokemon_chat_room.ui.dashboard;

import static android.content.Context.MODE_PRIVATE;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.pokemon_chat_room.R;
import com.example.pokemon_chat_room.adapter.MsgAdapter;
import com.example.pokemon_chat_room.adapter.MyItemBindAdapter;
import com.example.pokemon_chat_room.adapter.MyItemsAdapter;
import com.example.pokemon_chat_room.databinding.FragmentDashboardBinding;
import com.example.pokemon_chat_room.pojo.Address;
import com.example.pokemon_chat_room.pojo.Msg;
import com.example.pokemon_chat_room.pojo.MyItemsDto;
import com.example.pokemon_chat_room.pojo.Pokemon;
import com.example.pokemon_chat_room.request.OkHttp;
import com.example.pokemon_chat_room.util.MyImageView;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

public class DashboardFragment extends Fragment {


    boolean isGo = false;

    Dialog addressMapDialog;

    Dialog myItemsDialog;

    Spinner addressSpinner;

    int addNow = 1;

    Button goToButton;

    TextView addressTv;

    TextView stepTv;

    Address address = new Address();

    Timer timer;

    int index;

    int step;

    List<Address> addresses;

    OkHttp okHttp;

    Pokemon pokemonFind;

    Dialog findPokemonDialog;

    private SwipeRefreshLayout refreshLayout;


    public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String return_data = intent.getExtras().getString("data");
            String return_data2 = intent.getExtras().getString("catch");

            if (return_data2 != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int i = Integer.parseInt(return_data2);
                        if (i == 0) {
                            Toast.makeText(getContext(), "物品选择错误或无该物品", Toast.LENGTH_SHORT).show();
                            startFindPokemon();
                        } else {
                            myItemsDialog.dismiss();
                            findPokemonDialog.dismiss();
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    OkHttp okHttp = new OkHttp();
                                    JSONObject jsonObject = new JSONObject();
                                    SharedPreferences sharedPreferences = Objects.requireNonNull(getActivity()).getSharedPreferences("user", MODE_PRIVATE);
                                    String token = sharedPreferences.getString("token", "");
                                    jsonObject.put("token", token);
                                    jsonObject.put("pokemonId", pokemonFind.getId());
                                    jsonObject.put("itemsBaseId", i);
                                    try {
                                        JSONObject res = okHttp.Post(getContext(), "log-catch/catchPokemon", jsonObject);
                                        System.out.println(res);
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                startFindPokemon();
                                                Toast.makeText(getContext(), res.getString("message"), Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                            }).start();
                        }
                    }
                });
                System.out.println("return_data2:" + return_data2);
            }
            if (return_data == null) {
                return;
            }
            Msg msg = JSONObject.parseObject(return_data, Msg.class);
            Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    msgList.add(msg);
                    //当有新消息时，刷新ListView中的消息
                    adapter.notifyItemInserted(msgList.size() - 1);
                    //将LestView定位到最后一行
                    recyclerView.scrollToPosition(msgList.size() - 1);
                    skip++;
                }
            });
        }
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            adapter = new MsgAdapter(msgList);
            recyclerView.setAdapter(adapter);
        }
    };

    private StringBuilder sb = new StringBuilder();
    private List<Msg> msgList = new ArrayList<>();
    private MsgAdapter adapter;
    private RecyclerView recyclerView;  //对话显示框
    private EditText input_text;        //输入框
    private String time;                //获取时间
    private Button send;                //发送按钮
    private String name;                //从主活动获取的名字
    private String hisName;             //对方昵称，从自定义的receive线程中获取，便于和自己的昵称区分
    private String content;             //获取对话内容
    private String recMsg;
    boolean isRunning = false;          //判断线程是否运行
    boolean isSend = false;             //判断是否发送

    private int current = 0;

    private int skip = 0;

    private String post = "";
    private FragmentDashboardBinding binding;
    private MyReceiver receiver;


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        DashboardViewModel dashboardViewModel =
                new ViewModelProvider(this).get(DashboardViewModel.class);

        binding = FragmentDashboardBinding.inflate(inflater, container, false);

        View root = binding.getRoot();


        IntentFilter filter = new IntentFilter("com.example.pokemon_chat_room.ACTION");
        receiver = new MyReceiver();
        Objects.requireNonNull(getActivity()).getApplicationContext().registerReceiver(receiver, filter);

        Intent intent = Objects.requireNonNull(this.getActivity()).getIntent();
        //传入键值得到数据
        name = intent.getStringExtra("name");
        //获取实例
        input_text = (EditText) root.findViewById(R.id.input_text);
        refreshLayout = root.findViewById(R.id.swipe);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshLayout.setRefreshing(true);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("skip", current * 10 + skip);
                System.out.println("skip:" + (current * 10 + skip));
                OkHttp okHttp = new OkHttp();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject res = null;
                        try {
                            res = okHttp.Post(getContext(), "log-chat/getPage", jsonObject);
                            System.out.println(res);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        JSONArray data = res.getJSONArray("data");
                        if (data == null || data.size() == 0) {
                            return;
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 0; i < data.size(); i++) {
                                    Msg msg = data.getObject(i, Msg.class);
                                    msgList.add(i, msg);


                                }
                                current ++;
                                adapter.notifyItemRangeInserted(0, data.size());
                            }
                        });
                    }
                }).start();
                refreshLayout.setRefreshing(false);
            }
        });
        SharedPreferences sharedPreferences = Objects.requireNonNull(getActivity()).getSharedPreferences("user", MODE_PRIVATE);
        String token = sharedPreferences.getString("token", "");


        send = (Button) root.findViewById(R.id.send);
        goToButton = (Button) root.findViewById(R.id.go_to_btn);
        stepTv = root.findViewById(R.id.step_tv);
        addressTv = root.findViewById(R.id.address_tv);
        addressSpinner = root.findViewById(R.id.address_spinner);
        addressSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                addNow = position + 1;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        OkHttp okHttp = new OkHttp();

        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //显示时间
                time = getCurrentTime();
                String label = input_text.getText().toString();
                int type = 0;
                //显示信息
                if (!"".equals(label)) {  //发送信息不为空
                    if (label.charAt(0) == '#') {
                        Toast.makeText(root.getContext(), "指令错误！", Toast.LENGTH_SHORT).show();
                        type = 1;
                        // TODO 指令模块
                        return;
                    }
                    isSend = true;
                    int finalType = type;


                    // 通知适配器新元素添加

                    new Thread(new Runnable() {
                        @Override
                        public void run() {

                            try {
                                JSONObject json = new JSONObject();
                                json.put("token", token);
                                json.put("label", label);
                                json.put("type", finalType);
                                JSONObject jsonObject = okHttp.Post(root.getContext(), "log-chat/sendMsg", json);


                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }

                        }
                    }).start();


                    input_text.setText("");
                } else {
                    Toast.makeText(root.getContext(), "不可发送空信息！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //将RecyclerView和list建立联系(建立与适配器关系啥的)
        LinearLayoutManager layoutManager = new LinearLayoutManager(root.getContext());
        recyclerView = (RecyclerView) root.findViewById(R.id.msg_recycler_view);


        JSONObject json = new JSONObject();
        json.put("skip", current * 10 + skip);
        recyclerView.setLayoutManager(layoutManager);

        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    JSONObject jsonObject = okHttp.Post(root.getContext(), "log-chat/getPage", json);
                    JSONArray data = jsonObject.getJSONArray("data");
                    for (int i = 0; i < data.size(); i++) {
                        Msg msg = (Msg) data.getObject(i, Msg.class);
                        msgList.add(msg);
                    }
                    System.out.println(msgList);
                    Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            adapter = new MsgAdapter(msgList);
                            recyclerView.setAdapter(adapter);
                            recyclerView.scrollToPosition(adapter.getItemCount() - 1);
                            current ++;
                        }
                    });

//                    handler.handleMessage(new Message());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }).start();
        adapter = new MsgAdapter(msgList);
        recyclerView.setAdapter(adapter);


        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("token", sharedPreferences.getString("token", ""));
                try {
                    JSONObject res = okHttp.Post(getContext(), "address/getUserAddress", jsonObject);
                    if (res.getInteger("code") != 20007) {
                        return;
                    }
                    Address add = res.getJSONObject("data").toJavaObject(Address.class);
                    System.out.println(res);
                    address = add;
                    System.out.println(add);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            addressTv.setText(address.getName());
                            stepTv.setText(address.getLength().toString());
                            System.out.println("address:");
                        }
                    });
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

        goToButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isGo) {
                    Toast.makeText(getContext(), "请勿重复点击", Toast.LENGTH_SHORT).show();
                    return;
                }
                isGo = true;
                if (addNow == address.getId()) {
                    Toast.makeText(getContext(), "请勿选择相同地点", Toast.LENGTH_SHORT).show();
                    isGo = false;
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("routeId", address.getId() + "-" + addNow);
                        jsonObject.put("token", token);
                        try {
                            JSONObject res = okHttp.Post(getContext(), "address/getRoute", jsonObject);
                            String data = res.getString("data");
                            if (data == null) {
                                return;
                            }
                            addresses = JSONObject.parseArray(data, Address.class);
                            index = 0;
                            step = address.getLength();

                            startFindPokemon();

                            System.out.println(res);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }).start();
            }
        });

        addressTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View alertDialogView = getLayoutInflater().inflate(R.layout.address_map_layout, null, false);
                MyImageView image1 = alertDialogView.findViewById(R.id.address_map1);
                MyImageView image2 = alertDialogView.findViewById(R.id.address_map2);
                image1.setImageURL("poke/" + address.getImage());
                image2.setImageURL("poke/" + address.getMap());
                int width = getResources().getDisplayMetrics().widthPixels;
                int height = getResources().getDisplayMetrics().heightPixels;

                AlertDialog.Builder mapDialog = new AlertDialog.Builder(Objects.requireNonNull(getActivity()));

                mapDialog
                        .setView(alertDialogView)
                        .setTitle("地图");
                addressMapDialog = mapDialog.show();
            }
        });
        return root;
    }

    class MyDecoration extends RecyclerView.ItemDecoration {
        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            //outRect.set()中的参数分别对应左、上、右、下的间隔
            outRect.set(10, 10, 10, 10);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Objects.requireNonNull(getActivity()).getApplicationContext().unregisterReceiver(receiver);
        binding = null;
    }

    //获取当前时间
    public String getCurrentTime() {
        Date d = new Date();
        //设置显示的时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
        //以这种格式显示
        return sdf.format(d);
    }

    //子线程与主线程通过Handler来进行通信。子线程可以通过Handler来通知主线程进行UI更新。
    //Handler有两个主要的用途:(1)安排消息和可运行对象在将来的某个时间点执行;(2)将一个要在不同的线程上执行的动作编入队列。
//    private Handler handler = new Handler(Looper.myLooper()){
//        @Override
//        public void handleMessage(@NonNull Message msg) {
//            if(!recMsg.isEmpty()){
//                System.out.println("更新消息");
//                addNewMessage(content,0,time,hisName,his_imageId);  //刷新接收的消息
//            }
//        }
//    };

    public void addNewMessage(String msg, int type, String time, String name, int his_imageId) {
        Msg message = new Msg();
        msgList.add(message);
        //当有消息时，通知列表有新的数据插入，刷新recyclerview中消息
        adapter.notifyItemInserted(msgList.size() - 1);
        //将消息一直放在显示屏的底部不随意跑上去
        recyclerView.scrollToPosition(msgList.size() - 1);
    }

    public boolean findPokemon() {
        double rd = Math.random();
        return rd <= 0.32;
    }

    public void startFindPokemon() {
        OkHttp okHttp = new OkHttp();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {

                try {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            step -= 1;
                            if (step == -1) {
                                index++;
                                if (index >= addresses.size() - 1) {
                                    step = addresses.get(index).getLength();
                                    addressTv.setText(addresses.get(index).getName());
                                    Toast.makeText(getContext(), "你来到了" + addresses.get(index).getName(), Toast.LENGTH_SHORT).show();
                                    stepTv.setText(Integer.toString(step));
                                    address = addresses.get(index);
                                    timer.cancel();
                                    isGo = false;
                                    return;
                                }
                                step = addresses.get(index).getLength();
                                addressTv.setText(addresses.get(index).getName());
                                Toast.makeText(getContext(), "你来到了" + addresses.get(index).getName(), Toast.LENGTH_SHORT).show();
                                address = addresses.get(index);
                            }

                            stepTv.setText(Integer.toString(step));
                            if (findPokemon()) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        JSONObject jsonObject1 = new JSONObject();
                                        System.out.println(address.getName());
                                        jsonObject1.put("addressId", address.getId());
                                        try {
                                            JSONObject res = okHttp.Post(getContext(), "address/findPokemon", jsonObject1);
                                            System.out.println(res);
                                            pokemonFind = res.getJSONObject("data").toJavaObject(Pokemon.class);
                                            timer.cancel();


                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    View alertDialogView = getLayoutInflater().inflate(R.layout.find_pokemon_layout, null, false);
                                                    TextView pokemon_tv = alertDialogView.findViewById(R.id.pokemon_tv);
                                                    MyImageView pokemon_img = alertDialogView.findViewById(R.id.pokemon_img);

                                                    Button cancel_btn = alertDialogView.findViewById(R.id.cancel_btn);
                                                    Button submit_btn = alertDialogView.findViewById(R.id.submit_btn);
                                                    AlertDialog.Builder editInfoAlertDialog = new AlertDialog.Builder(Objects.requireNonNull(getActivity()));
                                                    editInfoAlertDialog
                                                            .setView(alertDialogView)
                                                            .setCancelable(false)
                                                            .setTitle("遭遇宝可梦");


                                                    pokemon_tv.setText(pokemonFind.getName());
                                                    pokemon_img.setImageURL("poke/" + pokemonFind.getImage());
                                                    cancel_btn.setOnClickListener(new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View v) {
                                                            findPokemonDialog.dismiss();
                                                            startFindPokemon();
                                                        }
                                                    });

                                                    submit_btn.setOnClickListener(new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View v) {
                                                            View alertDialogView = getLayoutInflater().inflate(R.layout.my_items_base_layout, null, false);
                                                            RecyclerView recyclerView = alertDialogView.findViewById(R.id.my_items_list);
                                                            Button close_btn = alertDialogView.findViewById(R.id.close_btn);
                                                            RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 5);
                                                            recyclerView.setLayoutManager(layoutManager);
                                                            recyclerView.addItemDecoration(new MyDecoration());

                                                            OkHttp okHttp = new OkHttp();

                                                            new Thread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    SharedPreferences mShared = Objects.requireNonNull(getActivity()).getSharedPreferences("user", MODE_PRIVATE);
                                                                    String token = mShared.getString("token", "");
                                                                    JSONObject jsonObject = new JSONObject();
                                                                    jsonObject.put("token", token);
                                                                    JSONObject post = null;
                                                                    try {
                                                                        post = okHttp.Post(getContext(), "items-base/getAll", jsonObject);
                                                                        JSONArray data = post.getJSONArray("data");
                                                                        List<MyItemsDto> list = new ArrayList<>();
                                                                        for (int i = 0; i < data.size(); i++) {
                                                                            list.add(data.getObject(i, MyItemsDto.class));
                                                                        }
                                                                        getActivity().runOnUiThread(new Runnable() {
                                                                            @Override
                                                                            public void run() {
                                                                                MyItemBindAdapter adapter = new MyItemBindAdapter(getContext(), list);
                                                                                recyclerView.setAdapter(adapter);
                                                                            }
                                                                        });
                                                                    } catch (IOException e) {
                                                                        throw new RuntimeException(e);
                                                                    }
                                                                    System.out.println(post);
                                                                }
                                                            }).start();

                                                            AlertDialog.Builder editInfoAlertDialog = new AlertDialog.Builder(Objects.requireNonNull(getActivity()));
                                                            editInfoAlertDialog
                                                                    .setView(alertDialogView)
                                                                    .setCancelable(false)
                                                                    .setTitle("我的道具");

                                                            myItemsDialog = editInfoAlertDialog.show();

                                                            close_btn.setOnClickListener(new View.OnClickListener() {
                                                                @Override
                                                                public void onClick(View v) {
                                                                    myItemsDialog.dismiss();
                                                                    startFindPokemon();
                                                                }
                                                            });
                                                        }
                                                    });
                                                    findPokemonDialog = editInfoAlertDialog.show();

                                                }
                                            });

                                        } catch (IOException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                }).start();

                            }
                        }
                    });
                } catch (Exception e) {
                    timer.cancel();
                }

                // TODO
            }
        }, 2 * 1000, 2 * 1000);
    }
}

